package com.cyx.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username+"/"+password);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] channels = req.getParameterValues("channel");
        //获取Cookie
        Cookie[] cookies = req.getCookies();
        //String loginTime = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(new Date());
        String loginTime = String.valueOf(System.currentTimeMillis());
        if (cookies == null){
        }else {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if ("loginTime".equals(cookie.getName())){
                    long v = Long.parseLong(cookie.getValue());
                    loginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(v));
                    System.out.println("上次登录时间为"+loginTime);
                }
            }
        }
        System.out.println(username+"/"+password);
        System.out.println(Arrays.toString(channels));
        Cookie cookie = new Cookie("loginTime",loginTime);
        cookie.setMaxAge(60*60*24);
        resp.addCookie(cookie);
        if(username.equals("admin") && password.equals("admin")){
            req.getRequestDispatcher("/hello").forward(req,resp);
        }
    }
}
